package com.aqielife.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

@Slf4j
@Controller
@RequestMapping("index")
public class IndexController {
    @GetMapping("/index")
    public String index(){
        return "index";
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        log.info("get1 start");
        String result = createStr();
        log.info("get1 end.");
        return result;
    }

    // 不会阻塞 惰性求值
    @ResponseBody
    @GetMapping("/hello2")
    public Mono<String> hello2(){
        // return Mono.just("hello WebFlux");
        log.info("get2 start");
        Mono<String> result = Mono.fromSupplier(this::createStr);   // 传提供者
        log.info("get2 end.");
        return result;
    }

    private String createStr() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
        }
        return "hello springMVC";
    }

    // 指定生产者类型
    @ResponseBody
    @GetMapping(value = "/hello3", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    private Flux<String> flux(){
        // jdk8 流产生数据
        Flux<String> result = Flux.fromStream(IntStream.range(1,5).mapToObj(i -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
            }
            return "flux data--" + i;
        }));
        return result;
    }
}
